home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1997 February / EnigmA AMIGA RUN 15 (1997)(G.R. Edizioni)(IT)[!][issue 1997-02][PLANET CD V].iso / progs / sviluppo / python-1.4 / lib / rfc822.py < prev    next >
Text File  |  1996-11-24  |  11KB  |  459 lines

  1. # RFC-822 message manipulation class.
  2. #
  3. # XXX This is only a very rough sketch of a full RFC-822 parser;
  4. # in particular the tokenizing of addresses does not adhere to all the
  5. # quoting rules.
  6. #
  7. # Directions for use:
  8. #
  9. # To create a Message object: first open a file, e.g.:
  10. #   fp = open(file, 'r')
  11. # (or use any other legal way of getting an open file object, e.g. use
  12. # sys.stdin or call os.popen()).
  13. # Then pass the open file object to the Message() constructor:
  14. #   m = Message(fp)
  15. #
  16. # To get the text of a particular header there are several methods:
  17. #   str = m.getheader(name)
  18. #   str = m.getrawheader(name)
  19. # where name is the name of the header, e.g. 'Subject'.
  20. # The difference is that getheader() strips the leading and trailing
  21. # whitespace, while getrawheader() doesn't.  Both functions retain
  22. # embedded whitespace (including newlines) exactly as they are
  23. # specified in the header, and leave the case of the text unchanged.
  24. #
  25. # For addresses and address lists there are functions
  26. #   realname, mailaddress = m.getaddr(name) and
  27. #   list = m.getaddrlist(name)
  28. # where the latter returns a list of (realname, mailaddr) tuples.
  29. #
  30. # There is also a method
  31. #   time = m.getdate(name)
  32. # which parses a Date-like field and returns a time-compatible tuple,
  33. # i.e. a tuple such as returned by time.localtime() or accepted by
  34. # time.mktime().
  35. #
  36. # See the class definition for lower level access methods.
  37. #
  38. # There are also some utility functions here.
  39.  
  40.  
  41. import regex
  42. import string
  43. import time
  44.  
  45.  
  46. _blanklines = ('\r\n', '\n')        # Optimization for islast()
  47.  
  48.  
  49. class Message:
  50.  
  51.     # Initialize the class instance and read the headers.
  52.     
  53.     def __init__(self, fp, seekable = 1):
  54.         self.fp = fp
  55.         self.seekable = seekable
  56.         self.startofheaders = None
  57.         self.startofbody = None
  58.         #
  59.         if self.seekable:
  60.             try:
  61.                 self.startofheaders = self.fp.tell()
  62.             except IOError:
  63.                 self.seekable = 0
  64.         #
  65.         self.readheaders()
  66.         #
  67.         if self.seekable:
  68.             try:
  69.                 self.startofbody = self.fp.tell()
  70.             except IOError:
  71.                 self.seekable = 0
  72.  
  73.  
  74.     # Rewind the file to the start of the body (if seekable).
  75.  
  76.     def rewindbody(self):
  77.         if not self.seekable:
  78.             raise IOError, "unseekable file"
  79.         self.fp.seek(self.startofbody)
  80.  
  81.  
  82.     # Read header lines up to the entirely blank line that
  83.     # terminates them.  The (normally blank) line that ends the
  84.     # headers is skipped, but not included in the returned list.
  85.     # If a non-header line ends the headers, (which is an error),
  86.     # an attempt is made to backspace over it; it is never
  87.     # included in the returned list.
  88.     #
  89.     # The variable self.status is set to the empty string if all
  90.     # went well, otherwise it is an error message.
  91.     # The variable self.headers is a completely uninterpreted list
  92.     # of lines contained in the header (so printing them will
  93.     # reproduce the header exactly as it appears in the file).
  94.  
  95.     def readheaders(self):
  96.         self.dict = {}
  97.         self.unixfrom = ''
  98.         self.headers = list = []
  99.         self.status = ''
  100.         headerseen = ""
  101.         firstline = 1
  102.         while 1:
  103.             line = self.fp.readline()
  104.             if not line:
  105.                 self.status = 'EOF in headers'
  106.                 break
  107.             # Skip unix From name time lines
  108.             if firstline and line[:5] == 'From ':
  109.                 self.unixfrom = self.unixfrom + line
  110.                     continue
  111.             firstline = 0
  112.             if self.islast(line):
  113.                 break
  114.             elif headerseen and line[0] in ' \t':
  115.                 # It's a continuation line.
  116.                 list.append(line)
  117.                 x = (self.dict[headerseen] + "\n " +
  118.                      string.strip(line))
  119.                 self.dict[headerseen] = string.strip(x)
  120.             elif ':' in line:
  121.                 # It's a header line.
  122.                 list.append(line)
  123.                 i = string.find(line, ':')
  124.                 headerseen = string.lower(line[:i])
  125.                 self.dict[headerseen] = string.strip(
  126.                     line[i+1:])
  127.             else:
  128.                 # It's not a header line; stop here.
  129.                 if not headerseen:
  130.                     self.status = 'No headers'
  131.                 else:
  132.                     self.status = 'Bad header'
  133.                 # Try to undo the read.
  134.                 if self.seekable:
  135.                     self.fp.seek(-len(line), 1)
  136.                 else:
  137.                     self.status = \
  138.                         self.status + '; bad seek'
  139.                 break
  140.  
  141.  
  142.     # Method to determine whether a line is a legal end of
  143.     # RFC-822 headers.  You may override this method if your
  144.     # application wants to bend the rules, e.g. to strip trailing
  145.     # whitespace, or to recognise MH template separators
  146.     # ('--------').  For convenience (e.g. for code reading from
  147.     # sockets) a line consisting of \r\n also matches.
  148.  
  149.     def islast(self, line):
  150.         return line in _blanklines
  151.  
  152.  
  153.     # Look through the list of headers and find all lines matching
  154.     # a given header name (and their continuation lines).
  155.     # A list of the lines is returned, without interpretation.
  156.     # If the header does not occur, an empty list is returned.
  157.     # If the header occurs multiple times, all occurrences are
  158.     # returned.  Case is not important in the header name.
  159.  
  160.     def getallmatchingheaders(self, name):
  161.         name = string.lower(name) + ':'
  162.         n = len(name)
  163.         list = []
  164.         hit = 0
  165.         for line in self.headers:
  166.             if string.lower(line[:n]) == name:
  167.                 hit = 1
  168.             elif line[:1] not in string.whitespace:
  169.                 hit = 0
  170.             if hit:
  171.                 list.append(line)
  172.         return list
  173.  
  174.  
  175.     # Similar, but return only the first matching header (and its
  176.     # continuation lines).
  177.  
  178.     def getfirstmatchingheader(self, name):
  179.         name = string.lower(name) + ':'
  180.         n = len(name)
  181.         list = []
  182.         hit = 0
  183.         for line in self.headers:
  184.             if hit:
  185.                 if line[:1] not in string.whitespace:
  186.                     break
  187.             elif string.lower(line[:n]) == name:
  188.                 hit = 1
  189.             if hit:
  190.                 list.append(line)
  191.         return list
  192.  
  193.  
  194.     # A higher-level interface to getfirstmatchingheader().
  195.     # Return a string containing the literal text of the header
  196.     # but with the keyword stripped.  All leading, trailing and
  197.     # embedded whitespace is kept in the string, however.
  198.     # Return None if the header does not occur.
  199.  
  200.     def getrawheader(self, name):
  201.         list = self.getfirstmatchingheader(name)
  202.         if not list:
  203.             return None
  204.         list[0] = list[0][len(name) + 1:]
  205.         return string.joinfields(list, '')
  206.  
  207.  
  208.     # The normal interface: return a stripped version of the
  209.     # header value with a name, or None if it doesn't exist.  This
  210.     # uses the dictionary version which finds the *last* such
  211.     # header.
  212.  
  213.     def getheader(self, name):
  214.         try:
  215.             return self.dict[string.lower(name)]
  216.         except KeyError:
  217.             return None
  218.  
  219.  
  220.     # Retrieve a single address from a header as a tuple, e.g.
  221.     # ('Guido van Rossum', 'guido@cwi.nl').
  222.  
  223.     def getaddr(self, name):
  224.         try:
  225.             data = self[name]
  226.         except KeyError:
  227.             return None, None
  228.         return parseaddr(data)
  229.  
  230.     # Retrieve a list of addresses from a header, where each
  231.     # address is a tuple as returned by getaddr().
  232.  
  233.     def getaddrlist(self, name):
  234.         # XXX This function is not really correct.  The split
  235.         # on ',' might fail in the case of commas within
  236.         # quoted strings.
  237.         try:
  238.             data = self[name]
  239.         except KeyError:
  240.             return []
  241.         data = string.splitfields(data, ',')
  242.         for i in range(len(data)):
  243.             data[i] = parseaddr(data[i])
  244.         return data
  245.  
  246.     # Retrieve a date field from a header as a tuple compatible
  247.     # with time.mktime().
  248.  
  249.     def getdate(self, name):
  250.         try:
  251.             data = self[name]
  252.         except KeyError:
  253.             return None
  254.         return parsedate(data)
  255.  
  256.  
  257.     # Access as a dictionary (only finds *last* header of each type):
  258.  
  259.     def __len__(self):
  260.         return len(self.dict)
  261.  
  262.     def __getitem__(self, name):
  263.         return self.dict[string.lower(name)]
  264.  
  265.     def has_key(self, name):
  266.         return self.dict.has_key(string.lower(name))
  267.  
  268.     def keys(self):
  269.         return self.dict.keys()
  270.  
  271.     def values(self):
  272.         return self.dict.values()
  273.  
  274.     def items(self):
  275.         return self.dict.items()
  276.  
  277.  
  278.  
  279. # Utility functions
  280. # -----------------
  281.  
  282. # XXX Should fix these to be really conformant.
  283. # XXX The inverses of the parse functions may also be useful.
  284.  
  285.  
  286. # Remove quotes from a string.
  287.  
  288. def unquote(str):
  289.     if len(str) > 1:
  290.         if str[0] == '"' and str[-1:] == '"':
  291.             return str[1:-1]
  292.         if str[0] == '<' and str[-1:] == '>':
  293.             return str[1:-1]
  294.     return str
  295.  
  296.  
  297. # Parse an address into (name, address) tuple
  298.  
  299. def parseaddr(address):
  300.     import string
  301.     str = ''
  302.     email = ''
  303.     comment = ''
  304.     backslash = 0
  305.     dquote = 0
  306.     space = 0
  307.     paren = 0
  308.     bracket = 0
  309.     seen_bracket = 0
  310.     for c in address:
  311.         if backslash:
  312.             str = str + c
  313.             backslash = 0
  314.             continue
  315.         if c == '\\':
  316.             backslash = 1
  317.             continue
  318.         if dquote:
  319.             if c == '"':
  320.                 dquote = 0
  321.             else:
  322.                 str = str + c
  323.             continue
  324.         if c == '"':
  325.             dquote = 1
  326.             continue
  327.         if c in string.whitespace:
  328.             space = 1
  329.             continue
  330.         if space:
  331.             str = str + ' '
  332.             space = 0
  333.         if paren:
  334.             if c == '(':
  335.                 paren = paren + 1
  336.                 str = str + c
  337.                 continue
  338.             if c == ')':
  339.                 paren = paren - 1
  340.                 if paren == 0:
  341.                     comment = comment + str
  342.                     str = ''
  343.                     continue
  344.         if c == '(':
  345.             paren = paren + 1
  346.             if bracket:
  347.                 email = email + str
  348.                 str = ''
  349.             elif not seen_bracket:
  350.                 email = email + str
  351.                 str = ''
  352.             continue
  353.         if bracket:
  354.             if c == '>':
  355.                 bracket = 0
  356.                 email = email + str
  357.                 str = ''
  358.                 continue
  359.         if c == '<':
  360.             bracket = 1
  361.             seen_bracket = 1
  362.             comment = comment + str
  363.             str = ''
  364.             email = ''
  365.             continue
  366.         if c == '#' and not bracket and not paren:
  367.             # rest is comment
  368.             break
  369.         str = str + c
  370.     if str:
  371.         if seen_bracket:
  372.             if bracket:
  373.                 email = str
  374.             else:
  375.                 comment = comment + str
  376.         else:
  377.             if paren:
  378.                 comment = comment + str
  379.             else:
  380.                 email = email + str
  381.     return string.strip(comment), string.strip(email)
  382.  
  383.  
  384. # Parse a date field
  385.  
  386. _monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
  387.       'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  388.  
  389. def parsedate(data):
  390.     # XXX This still mostly ignores timezone matters at the moment...
  391.     data = string.split(data)
  392.     if data[0][-1] == ',':
  393.         # There's a dayname here. Skip it
  394.         del data[0]
  395.     if len(data) == 4:
  396.         s = data[3]
  397.         i = string.find(s, '+')
  398.         if i > 0:
  399.             data[3:] = [s[:i], s[i+1:]]
  400.         else:
  401.             data.append('') # Dummy tz
  402.     if len(data) < 5:
  403.         return None
  404.     data = data[:5]
  405.     [dd, mm, yy, tm, tz] = data
  406.     if not mm in _monthnames:
  407.         return None
  408.     mm = _monthnames.index(mm)+1
  409.     tm = string.splitfields(tm, ':')
  410.     if len(tm) == 2:
  411.         [thh, tmm] = tm
  412.         tss = '0'
  413.     else:
  414.         [thh, tmm, tss] = tm
  415.     try:
  416.         yy = string.atoi(yy)
  417.         dd = string.atoi(dd)
  418.         thh = string.atoi(thh)
  419.         tmm = string.atoi(tmm)
  420.         tss = string.atoi(tss)
  421.     except string.atoi_error:
  422.         return None
  423.     tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0)
  424.     return tuple
  425.  
  426.  
  427. # When used as script, run a small test program.
  428. # The first command line argument must be a filename containing one
  429. # message in RFC-822 format.
  430.  
  431. if __name__ == '__main__':
  432.     import sys, os
  433.     file = os.path.join(os.environ['HOME'], 'Mail/drafts/,1')
  434.     if sys.argv[1:]: file = sys.argv[1]
  435.     f = open(file, 'r')
  436.     m = Message(f)
  437.     print 'From:', m.getaddr('from')
  438.     print 'To:', m.getaddrlist('to')
  439.     print 'Subject:', m.getheader('subject')
  440.     print 'Date:', m.getheader('date')
  441.     date = m.getdate('date')
  442.     if date:
  443.         print 'ParsedDate:', time.asctime(date)
  444.     else:
  445.         print 'ParsedDate:', None
  446.     m.rewindbody()
  447.     n = 0
  448.     while f.readline():
  449.         n = n + 1
  450.     print 'Lines:', n
  451.     print '-'*70
  452.     print 'len =', len(m)
  453.     if m.has_key('Date'): print 'Date =', m['Date']
  454.     if m.has_key('X-Nonsense'): pass
  455.     print 'keys =', m.keys()
  456.     print 'values =', m.values()
  457.     print 'items =', m.items()
  458.     
  459.